
package pri.syl.xiaowu.websocket.netty.server.handler.core.factory;

import pri.syl.xiaowu.websocket.core.domain.HttpUpgradeRequest;
import pri.syl.xiaowu.websocket.core.template.WebsocketChannelTemplate;
import pri.syl.xiaowu.websocket.core.template.WebsocketRouteTemplate;
import pri.syl.xiaowu.websocket.netty.server.handler.HttpServerHandler;
import pri.syl.xiaowu.websocket.netty.server.handler.WebsocketServerHandler;
import pri.syl.xiaowu.websocket.netty.server.handler.core.factory.constant.IdleStateConstant;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @Author YunLong
 * @Date 2021/7/18 19:07
 * @Description netty过滤链
 **/
public class ChannelPipelineFactory {

    private ChannelPipelineFactory() {
    }

    public static void upgradeWebsocketPipeline(Channel channel, int readTimeoutMilli, HttpUpgradeRequest request, WebsocketRouteTemplate websocketRouteTemplate) {
        ChannelPipeline pipeline = channel.pipeline();
        pipeline.remove(IdleStateHandler.class);
        pipeline.remove(HttpServerHandler.class);
        pipeline.addFirst(new IdleStateHandler(readTimeoutMilli,
                IdleStateConstant.WEBSOCKET_WRITER_IDLE_TIME,
                IdleStateConstant.WEBSOCKET_ALL_IDLE_TIME));
        WebsocketChannelTemplate channelTemplate = new WebsocketChannelTemplate(channel);
        pipeline.addLast(new WebsocketServerHandler(websocketRouteTemplate, channelTemplate));
        websocketRouteTemplate.upgradeSuccessEvent(request, channelTemplate);
    }
}
